package com.lch.designpattern.proxy.dbroute.proxy;

import com.lch.designpattern.proxy.dbroute.IOrderService;
import com.lch.designpattern.proxy.dbroute.Order;
import com.lch.designpattern.proxy.dbroute.db.DynamicDataSourceEntity;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: liuchenhui
 * @create: 2019-04-18 22:14
 **/
public class OrderServiceStaticProxy implements IOrderService {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");

    private IOrderService orderService;

    public OrderServiceStaticProxy(IOrderService orderService) {
        this.orderService = orderService;
    }

    @Override
    public int createOrder(Order order) {
        Long time = order.getCreateTime();
        Integer dbRoute = Integer.valueOf(dateFormat.format(new Date(time)));
        System.out.println("静态代理类自动分配到【DB_" + dbRoute + "】数据源动态切换");
        DynamicDataSourceEntity.set(dbRoute);

        this.orderService.createOrder(order);
        DynamicDataSourceEntity.restore();
        return 0;
    }
}
